<template>
  <view class="my-container">
    <!-- 头像区域 -->
    <view class="avatar-section">
      <view class="avatar-wrapper">
        <!-- <image 
          class="avatar" 
          src="/static/images/default-avatar.png" 
          mode="aspectFill"
        /> -->
      </view>
    </view>

    <!-- 用户名称 -->
    <view class="user-name">
      <text class="name">{{ userName }}</text>
      <!-- 添加冻结状态显示 -->
      <view class="freeze-tag" v-if="isFrozen">
        <text class="freeze-text">已冻结</text>
      </view>
    </view>

    <!-- 信息卡片 -->
    <view class="info-card">
      <!-- 余额信息 -->
      <view class="info-row">
        <text class="label">SHJC积分余额</text>
        <text class="value">{{ balance }}</text>
      </view>
      <view class="divider"></view>

      <!-- 卡片数量 -->
      <view class="info-row">
        <text class="label">卡片数量</text>
        <text class="value">{{ cardCount }} 张</text>
      </view>
      <view class="divider"></view>

      <!-- 账单 -->
      <view class="info-row" @click="handleBillClick">
        <text class="label">账单</text>
        <view class="value-wrapper">
          <text class="value">{{ bill }}</text>
        </view>
      </view>

      <view class="info-row" v-if="isFrozen">
        <text class="label">冻结SHJC积分</text>
        <view class="value-wrapper">
          <text class="value">{{ freezeAccount }}</text>
        </view>
      </view>


       <view class="info-row" v-if="isFrozen">
        <text class="label">冻结卡片数量</text>
        <view class="value-wrapper">
          <text class="value">{{ freezeCard }}</text>
        </view>
      </view>
    </view>

    <!-- 底部按钮组 -->
    <view class="button-group">
      <button class="action-btn" @click="handleComplete">兑换</button>
      <button class="action-btn" @click="handleTransfer">转赠</button>
    </view>
  </view>
</template>

<script>
import authApi from "@/asstes/api/auth";

export default {
  name: "My",
  data() {
    return {
      balance: "0.00",
      cardCount: "0",
      bill: "-",
      userName: "用户名称",
      freezeAccount: "",
      freezeCard:null,
      isFrozen: false,
      socket: null
    };
  },
  async onLoad() {
    this.getCurrentUserInfo();
    this.connectWebSocket();
  },
  onUnload() {
    if (this.socket) {
      this.socket.close();
    }
    if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
  },
  methods: {
    connectWebSocket() {
      // 定时发送心跳
      this.heartbeatTimer = setInterval(() => {
        if (this.socket.readyState === this.socket.OPEN) {
          this.socket.send({
            data: 'ping'
          });
        }
      }, 30000);
      // 动态判断环境（开发环境可能需代理）
      const isDev = process.env.NODE_ENV === 'development';
      const wsUrl = isDev ? 'ws://www.pc.sanhuijucai.com/ws/message' : 'wss://your-domain.com/ws/message';
      
      this.socket = uni.connectSocket({
        url: wsUrl,
        success: () => {
          console.log('WebSocket 连接初始化');
        }
      });

      // 监听事件
      this.socket.onOpen(() => {
        console.log('WebSocket 连接成功');
        // 发送认证信息（若需要）
        this.socket.send({
          data: JSON.stringify({ type: 'auth', token: '用户token' })
        });
      });

      this.socket.onMessage((res) => {
        if (res.data !== "pong") { 
          const message = JSON.parse(res.data);
          console.log("接收到消息：", message)
          if (message.freezeStatus) { 
            console.log("freezeStatus", message.freezeStatus)
            if (message.freezeStatus === 1) { 
              uni.showModal({
                title: "账户异常通知",
                content: `该账户已被冻结，无法进行交易`,
                success: (res) => {
                  console.log("res", res);
                  if (res.confirm) {  
                    console.log("用户点击确定");
                    this.isFrozen = true
                  }
                },
              });
            }

            if (message.freezeStatus === 0) { 
              uni.showModal({
                title: "账户恢复通知",
                content: `该账户已解冻`,
                success: (res) => {
                  console.log("res", res);
                  if (res.confirm) {  
                    console.log("用户点击确定");
                    this.isFrozen = false
                  }
                },
              });
            }
      
              return
          }
        }
      });

      this.socket.onError((err) => {
        console.error('WebSocket 错误:', err);
        // 断线重连
        setTimeout(() => this.connectWebSocket(), 3000);
      });

      this.socket.onClose(() => {
        console.log('WebSocket 连接关闭');
      });
    },
    async getCurrentUserInfo() {
      try {
        const userInfo = JSON.parse(localStorage.getItem("userInfo"));
        this.userInfo = userInfo;
        console.log("用户信息:", userInfo);
        const data = {
          userId: 0,
          sysUserId: userInfo.userId,
        };
        const response = await authApi.getUserInfo(data);
        console.log("用户信息:", response);
        if (response.code === 200) {
          if (response.user) {
            this.cardCount = response.user.cardCount;
            this.balance = response.user.balance;
            this.freezeAccount = response.user.freezeAccount;
            this.isFrozen = response.user.status === 0;
            this.userName = response.user.username;
          }
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        uni.showToast({
          title: "获取用户信息失败",
          icon: "none",
        });
      }
    },
    handleComplete() {
      // 兑换操作 - 使用 navigateTo 而不是 switchTab
      uni.navigateTo({
        url: "/pages/exchange/index",
      });
    },

    handleTransfer() {
      // 转赠操作 - 这个是 tabBar 页面，所以使用 switchTab
      uni.switchTab({
        url: "/pages/transfer/index",
      });
    },

    handleBillClick() {
      // 修改为 navigateTo
      uni.navigateTo({
        url: "/pages/bill/index",
      });
    },
  },
};
</script>

<style lang="scss">
.my-container {
  min-height: 100vh;
  background: #fff;
  padding: 20rpx;
  box-sizing: border-box;
}

.user-name {
  text-align: center;
  margin-bottom: 20rpx;
  font-size: 40rpx;
  color: #333;
}

.avatar-section {
  display: flex;
  justify-content: center;
  padding: 40rpx 0;

  .avatar-wrapper {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    border: 1px solid #eee;
    overflow: hidden;
    background: #fff;

    .avatar {
      width: 100%;
      height: 100%;
    }
  }
}

.info-card {
  background: #fff;
  padding: 0 30rpx;
  border-radius: 4rpx;
  margin-bottom: 40rpx;

  .info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;

    .label {
      font-size: 28rpx;
      color: #333;
    }

    .value-wrapper {
      display: flex;
      align-items: center;

      .value {
        font-size: 28rpx;
        color: #666;
      }

      .icon-arrow {
        font-size: 24rpx;
        color: #999;
        margin-left: 10rpx;
      }
    }

    &:active {
      background: #f9f9f9;
    }
  }

  .divider {
    height: 1px;
    background: #f5f5f5;
    margin: 0 -30rpx;
  }
}

.button-group {
  display: flex;
  justify-content: space-between;
  padding: 0 30rpx;
  margin-top: 60rpx;

  .action-btn {
    width: 48%;
    height: 88rpx;
    line-height: 88rpx;
    background: #333;
    color: #fff;
    font-size: 32rpx;
    border-radius: 14rpx;
    border: 1px solid #fff;
    transition: all 0.3s;

    &:active {
      opacity: 0.8;
      background: #fff;
      color: #333;
    }
  }
}

.freeze-tag {
  display: inline-flex;
  align-items: center;
  background-color: #ff4d4f; /* 红色背景 */
  border-radius: 12px; /* 圆角 */
  padding: 4px 8px; /* 内边距 */
  margin-left: 8px; /* 与用户名称的间距 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  animation: pulse 1.5s infinite; /* 添加呼吸动画 */
}

.freeze-text {
  font-size: 12px;
  color: #ffffff; /* 白色文字 */
  margin-left: 4px; /* 图标与文字的间距 */
}

/* 呼吸动画效果 */
@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}
</style>
